package wangxiaotao.tools;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import wangxiaotao.properties.MyMinioProperties;
import wangxiaotao.utils.MinioUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class MinioTool {
    private final MyMinioProperties minioProperties;


    /**
     * 存储用户的头像数据
     * @param file
     * @return 返回链接
     */
    public String saveUserImage(MultipartFile[] file, String prefixName) {
        String[] userAvatar = MinioUtils.uploadObjectBatchByBucket(minioProperties.getBucketName(), prefixName, file, minioProperties.getUserAvatarPath());
        Assert.notNull(userAvatar,"头像文件添加失败");
        return getFileRealPath()+userAvatar[0];
    }
    /**
     * 房间图片上传
     * @param fileList
     * @return
     */
    public String saveBatchRoomImage(Integer floor,String prefixName,MultipartFile[] fileList) {
        String[] paths = MinioUtils.uploadObjectBatchByBucket(minioProperties.getBucketName(),prefixName, fileList, minioProperties.getRoomImagePath(), "f" + floor);
        Assert.notNull(paths,"房间图片添加失败");
        return Arrays.stream(paths).map(s->getFileRealPath()+s).collect(Collectors.joining("|"));
    }

    /**
     * 批量删除图片
     * @param floor
     * @param prefixName
     * @return
     */
    public boolean deleteBatch(Integer floor, String prefixName) {
        List<String> list = MinioUtils.listObjectByBucket(minioProperties.getBucketName(),minioProperties.getRoomImagePath(),"f"+floor,prefixName);
        if (!list.isEmpty()){
            for (String s:list){
                MinioUtils.removeObjectByBucketName(minioProperties.getBucketName(),s);
            }
        }
        return true;
    }


    /**
     * 上传banner
     * @param file
     */
    public String saveBannerImage(MultipartFile file) {
        String banners = MinioUtils.uploadObjectByBucket(minioProperties.getBucketName(), "banners", file);
        return getFileRealPath()+banners;
    }



    protected String getFileRealPath(){
        return "http://"+minioProperties.getEndpoint()+":"+minioProperties.getPort()
                +"/"+minioProperties.getBucketName()+"/";
    }

}
